<template>
  <div class="favorites">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>好名好运AI</h1>
          <el-menu mode="horizontal" router class="nav-menu">
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/name-generator">取名</el-menu-item>
            <el-menu-item index="/history">历史记录</el-menu-item>
            <el-menu-item index="/favorites">收藏</el-menu-item>
          </el-menu>
        </div>
      </el-header>

      <el-main>
        <h2>我的收藏</h2>
        
        <el-alert
          title="数据存储提示"
          type="warning"
          description="收藏数据存储在浏览器本地缓存中，清除浏览器缓存将导致数据丢失。请及时导出或保存重要的名字内容。"
          show-icon
          :closable="false"
          class="storage-alert"
        />
        
        <div v-if="store.favorites.length === 0" class="empty-state">
          <el-empty description="暂无收藏名字">
            <el-button type="primary" @click="$router.push('/name-generator')">去生成名字</el-button>
          </el-empty>
        </div>

        <div v-else class="favorites-list">
          <el-row justify="end" class="operation-row">
            <el-button type="success" @click="exportFavoritesData" class="export-btn">
              <el-icon><Download /></el-icon> 导出收藏
            </el-button>
            <el-button type="danger" @click="clearAllFavorites" :disabled="store.favorites.length === 0">
              清空全部收藏
            </el-button>
          </el-row>
          
          <el-row :gutter="20">
            <el-col 
              v-for="favorite in store.favorites" 
              :key="favorite.id"
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
            >
              <el-card class="favorite-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <div class="full-names">
                      <div v-for="(baby, babyIndex) in favorite.nameGroup.fullNames" :key="babyIndex">
                        <span class="baby-name">{{ baby.fullName }}</span>
                        <span class="baby-gender">({{ baby.gender }})</span>
                      </div>
                    </div>
                    <el-button
                      type="danger"
                      link
                      @click="deleteFavorite(favorite.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </template>
                
                <div class="favorite-details">
                  <p class="favorite-date">收藏于 {{ formatDate(favorite.date) }}</p>
                  <div class="name-details">
                    <p><strong>含义：</strong>{{ favorite.nameGroup.meaning }}</p>
                    <p v-if="favorite.nameGroup.relationMeaning"><strong>关联含义：</strong>{{ favorite.nameGroup.relationMeaning }}</p>
                    <p><strong>五行：</strong>{{ favorite.nameGroup.wuxing }}</p>
                    <p><strong>生肖：</strong>{{ favorite.nameGroup.zodiac }}</p>
                    <p><strong>音韵：</strong>{{ favorite.nameGroup.phonetics }}</p>
                    <p><strong>字形：</strong>{{ favorite.nameGroup.structure }}</p>
                  </div>
                  
                  <div class="input-details">
                    <el-collapse>
                      <el-collapse-item title="查看生成条件">
                        <p><strong>姓氏：</strong>{{ favorite.input.surname }}</p>
                        <p><strong>出生日期：</strong>{{ favorite.input.birthDate }}</p>
                        <p><strong>出生时辰：</strong>{{ favorite.input.birthTime || '未知' }}</p>
                        <p><strong>性别：</strong>{{ favorite.input.genders.join(', ') }}</p>
                        <p v-if="favorite.input.avoidWords">
                          <strong>忌讳字词：</strong>{{ favorite.input.avoidWords }}
                        </p>
                        <p v-if="favorite.input.isMultipleBirth">
                          <strong>多胞胎：</strong>{{ favorite.input.multipleCount }}胞胎
                        </p>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
      <Footer />
    </el-container>
  </div>
</template>

<script setup>
import { useNameStore } from '../stores/nameStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { Download } from '@element-plus/icons-vue'
import Footer from '../components/Footer.vue'

const store = useNameStore()
const router = useRouter()

function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

async function deleteFavorite(id) {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条收藏吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    store.deleteFavorite(id)
    ElMessage.success('收藏已删除')
  } catch {
    // 用户取消删除
  }
}

async function clearAllFavorites() {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有收藏吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清空收藏
    store.favorites.splice(0, store.favorites.length)
    ElMessage.success('所有收藏已清空')
  } catch {
    // 用户取消操作
  }
}

function exportFavoritesData() {
  try {
    const dataStr = store.exportFavorites()
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr)
    
    // 创建下载链接
    const exportFileDefaultName = '好名好运AI_收藏_' + dayjs().format('YYYYMMDD') + '.json'
    
    const linkElement = document.createElement('a')
    linkElement.setAttribute('href', dataUri)
    linkElement.setAttribute('download', exportFileDefaultName)
    linkElement.click()
    
    ElMessage.success('收藏导出成功')
  } catch (error) {
    console.error('导出收藏时出错:', error)
    ElMessage.error('导出失败，请重试')
  }
}
</script>

<style scoped>
.favorites {
  min-height: 100vh;
}

.favorites-list {
  padding: 20px;
}

.operation-row {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.export-btn {
  margin-right: auto;
}

.favorite-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.favorite-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.full-names {
  flex: 1;
}

.baby-name {
  font-weight: bold;
  margin-right: 5px;
}

.baby-gender {
  color: #606266;
  font-size: 0.9em;
}

.favorite-details {
  font-size: 14px;
  line-height: 1.6;
}

.favorite-date {
  color: #909399;
  margin-bottom: 10px;
  font-size: 0.9em;
}

.name-details {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.name-details p {
  margin: 8px 0;
}

.input-details {
  margin-top: 15px;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.el-header {
  background-color: #fff;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: auto;
  min-height: 60px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
  white-space: nowrap;
}

.nav-menu {
  border-bottom: none;
  height: 60px;
  background-color: #fff !important;
}

:deep(.el-menu--horizontal) {
  border-bottom: none !important;
}

:deep(.el-menu-item) {
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  color: #2c3e50;
}

:deep(.el-menu-item.is-active) {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

:deep(.el-menu-item:hover) {
  color: #409EFF;
  background-color: transparent;
}

@media (max-width: 768px) {
  .favorites-list {
    padding: 10px;
  }
  
  .favorite-card {
    margin-bottom: 15px;
  }
  
  .name-details {
    padding: 10px;
  }
}

.storage-alert {
  margin-bottom: 20px;
}
</style> 